package com.itheima.cookie;

import javafx.scene.shape.ClosePathBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@WebServlet("/lastTimeCookie")
public class LastTimeCookie extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //先获取cookie的值
        Cookie[] cookies = request.getCookies();
        //调用方法获取是否有该cookie的值
        Cookie cookie = getCookieName(cookies, "lastTimeCookie");

        //判断cookie是否为空
        //字符转换
        response.setContentType("text/html;charset=UTF-8");
        //浏览器输出对象
        PrintWriter pw = response.getWriter();
        if (cookie == null) {
            pw.write("欢迎首次登录");
        }else{
            String value = cookie.getValue();
            pw.write("欢迎回来上次登录时间为:" + value);
        }

        //创建新的Cookie对象属性为LastTimeCookie将上次访问的值覆盖
        Cookie ck = new Cookie("lastTimeCookie",new Date().toLocaleString().replace(" ","-"));

        //设置持久化时间(单位为秒)
        ck.setMaxAge(60*60*24*30);

        //保存Cookie
        response.addCookie(ck);
    }

    private static Cookie getCookieName(Cookie[] cookies, String cookie) {
       //判断cookie是否为空,是就返回null
        if (cookies != null) {
            //遍历比较cookie的属性
            for (Cookie c : cookies) {
                if (c.getName().equals(cookie)) {
                    return c;
                }
            }
        }
        return null;
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
